package com.lg.config;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lg.entity.SysPermission;
import com.lg.entity.SysRole;
import com.lg.entity.UserInfo;
import com.lg.repositories.UserInfoRepository;
@Component
public class MyRealm extends AuthorizingRealm {
	@Autowired
	private UserInfoRepository userInfoRepository;
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		String username = (String) token.getPrincipal();
		String credentials = (String) token.getCredentials();
		UserInfo userInfo = userInfoRepository.findByUsername(username);
		
		if(null == userInfo) {
			return null ;
		}
		
		SimpleAuthenticationInfo authenticationInfo  = new SimpleAuthenticationInfo(userInfo, //用户名
				userInfo.getPassword(), //数据库加盐后的密码
				ByteSource.Util.bytes(userInfo.getSalt()),
				                     getName());
		return authenticationInfo;
	}

	
	
	
	
	
	
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		 SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		 UserInfo userInfo = (UserInfo) principals.getPrimaryPrincipal();
		 
		 for (SysRole role : userInfo.getRoleList()) {
			 authorizationInfo.addRole(role.getRole());
			 for (SysPermission p : role.getPermissions()) {
				 authorizationInfo.addStringPermission(p.getPermission());
			}
		}
		return authorizationInfo;
	}

	


}
